package com.bitdf.txing.users.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.valid.SaveGroup;
import com.bitdf.txing.common.vo.UserInfoVo;
import com.bitdf.txing.users.entity.UserPermissionEntity;
import com.bitdf.txing.users.entity.UserRoleEntity;
import com.bitdf.txing.users.entity.UserRolePermRelateEntity;
import com.bitdf.txing.users.service.UserPermissionService;
import com.bitdf.txing.users.service.UserRolePermRelateService;
import com.bitdf.txing.users.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



/**
 * 
 *
 * @author lizhiwei
 * @email 
 * @date 2023-09-02 21:43:03
 */
@RestController
@RequestMapping("${txing.request.path.users}/roleperm")
public class UserRolePermRelateController {
    @Autowired
    private UserRolePermRelateService userRolePermRelateService;
    @Autowired
    private UserPermissionService userPermissionService;
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 查询某用户ID拥有的所有权限
     * @return
     */
    @SaCheckLogin
    @GetMapping("/perms/get/loginId")
    public R getAllPermsByLoginId(@RequestParam("loginId") Long loginId) {
        UserInfoVo userInfoVo = (UserInfoVo) StpUtil.getSession().get("user");
        Long roleId = userInfoVo.getRoleId();
        List<UserPermissionEntity> perms = userRolePermRelateService.getPermsByRoleId(roleId.toString());
        List<String> collect = perms.stream().map((item) -> {
            return item.getName();
        }).collect(Collectors.toList());
        return R.ok(collect);
    }

    /**
     * 查询某用户ID拥有的所有权限
     * @return
     */
    @SaCheckLogin
    @GetMapping("/roles/get/loginId")
    public R getAllRolesByLoginId(@RequestParam("loginId") Long loginId) {
        UserInfoVo userInfoVo = (UserInfoVo) StpUtil.getSession().get("user");
        Long roleId = userInfoVo.getRoleId();
        UserRoleEntity entity = userRoleService.getById(roleId);
        List<String> list = new ArrayList<>();
        list.add(entity.getName());
        return R.ok(list);
    }

    /**
     * 查询某角色拥有的所有权限
     */
    @SaCheckLogin
    @GetMapping("/perms/get/{id}")
    public R info(@PathVariable("id") String roleId){

        List<UserPermissionEntity> collect = userRolePermRelateService.getPermsByRoleId(roleId);

        return R.ok(collect);
    }

    /**
     *  查询某权限被哪些角色所拥有
     */
    @SaCheckLogin
    @GetMapping("/roles/get/{permId}")
    public R getRolesByPermId(@PathVariable("permId") String permId){
        QueryWrapper<UserRolePermRelateEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserRolePermRelateEntity::getPermId, permId);
        List<UserRolePermRelateEntity> list = userRolePermRelateService.list(wrapper);
        // 查出这些关联的权限的具体信息， 并封装成list
        List<UserRoleEntity> collect = list.stream().map((item) -> {
            UserRoleEntity entity = userRoleService.getById(item.getRoleId());
            return entity;
        }).collect(Collectors.toList());
        return R.ok(collect);
    }

    /**
     * 创建新关联
     */
    @SaCheckPermission("user:role:perm:relate:save")
    @SaCheckLogin
    @RequestMapping("/save")
    public R save(@Validated(SaveGroup.class) @RequestBody UserRolePermRelateEntity userRolePermRelate, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
		userRolePermRelateService.save(userRolePermRelate);
        return R.ok();
    }

    /**
     * 删除
     */
    @SaCheckPermission("user:role:perm:relate:delete")
    @SaCheckLogin
    @PostMapping("/delete")
    public R delete(@RequestBody String[] ids){
		userRolePermRelateService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
